package com.zk.config.api.factory;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.support.PropertiesLoaderSupport;
import org.springframework.util.CollectionUtils;
import com.zk.config.api.client.ConfigClient;
import lombok.Setter;

public class PropertiesFactoryBean  extends PropertiesLoaderSupport
implements FactoryBean<Properties>, InitializingBean{

	@Setter
	private ConfigClient[] configClient;
	private Properties singletonInstance;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		if(singletonInstance != null) {
			mergeProperties();
		} else {
			singletonInstance = mergeProperties();
		}
	}

	@Override
	public Properties getObject() throws Exception {
		if (this.singletonInstance == null) {
			this.singletonInstance = new Properties();
		}
		return this.singletonInstance;
	}

	@Override
	public Class<?> getObjectType() {
		return Properties.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}
	
	@Override
	protected Properties mergeProperties() throws IOException {
		Properties result = new Properties();
		loadProperties(result);

		if (this.localProperties != null) {
			for (Properties localProp : this.localProperties) {
				CollectionUtils.mergePropertiesIntoMap(localProp, result);
			}
		}
		
		if (result != null && singletonInstance != null) {
			if (this.localOverride) {
				Enumeration en;
				for (en = result.propertyNames(); en.hasMoreElements();) {
					String key = (String) en.nextElement();
					if(!singletonInstance.containsKey(key)) {
						singletonInstance.put(key, result.getProperty(key));
					}
				}
			} else {
				singletonInstance.putAll(result);
			}
		}

		return singletonInstance;
	}
}
